<template>
  <n-upload
      ref="uploadImage"
      :action="actionurl"
      list-type="image-card"
      :file-list="filelistvalue"
      :custom-request="httpupload"
      :on-preview="yulan"
      :on-update:file-list="changefile"
      :on-remove="removefile"
  />
  <n-modal
      v-model:show="showModal"
      preset="card"
      class="max-w-3/5 max-h-3/5"
      :title="imgtitle"
      :on-close="guanbi"
  >
    <img :src="previewImageUrl" style="width: 100%" :alt="imgtitle">
  </n-modal>
</template>

<script setup name="upimg">
import {useRoute, useRouter} from "vue-router";
import http from "@/request/request"
import api from "@/request/api"
import {useDialog, useMessage, NImage} from "naive-ui";

const router = useRouter()
const route = useRoute()
const message = useMessage()
const dialog = useDialog()
const uploadImage=ref(null)
const actionurl = ref(import.meta.env.VITE_RES_URL?import.meta.env.VITE_RES_URL + api.upload : "/proxy/" + api.upload)
const filelistvalue = ref([])
// 图片预览
const showModal=ref(false)
const imgtitle=ref("")
const previewImageUrl = ref("")

const emit = defineEmits(["changefile"])
const props = defineProps({
  value:{
    type:Array,
    default:[],
  },
  max:{
    type:Number,
    default:1,
    validator(value) {
      return value >= 1;
    },
  },
})
// 文件列表改变的回调
const changefile=(fileList)=>{
  filelistvalue.value = fileList
}

const yulan=(file)=>{
  previewImageUrl.value = file.url
  imgtitle.value = file.name
  showModal.value = true
}
const guanbi=()=>{
  showModal.value = false
  previewImageUrl.value = ""
  imgtitle.value = ""
}
// 自定义上传
const httpupload=(fileinfo)=>{
  console.log(fileinfo,"看看是什么东西")
  const formData = new FormData()
  formData.append("file",fileinfo.file.file)
  http.upload(formData).then(res=>{
    if(res.status===200 && res.data.code === 0){
      const shuju = res.data.data
      console.log(shuju,"怎么没有url")
      const jieguo = {...fileinfo.file,name:shuju.filename || shuju.id,status:"finished",url:shuju.url,thumbnailUrl:shuju.url}
      delete jieguo.file
      console.log(jieguo,"怎么没有url")
      message.success("上传成功")
      fileinfo.onFinish()
      filelistvalue.value = [jieguo]
      emit("changefile",jieguo.url)
    }
  })
}
// 移除图片
const removefile=(fileinfo,filelist)=>{
  console.log(fileinfo,filelist,"移除图片回调")
  filelistvalue.value = []
}

// 监听传入的图片列表
watch(()=>props.value,()=>{
  if(props.value.length > props.max){
    filelistvalue.value = props.value.slice(0,props.max)
  }else{
    filelistvalue.value = props.value
  }
})
</script>


<style scoped>

</style>